<template>
  <div v-loading="loading" class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>订单录入</span>
      </div>
      <el-form
        ref="submitForm"
        v-loading="formLoading"
        :model="submitForm"
        :rules="submitFormRules"
        label-width="120px"
        label-position="right"
        class="submit-form"
      >
        <div class="info_group">
          <div class="info_section" />
          <div class="info_title">基本信息</div>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单日期" prop="orderDate">
              <el-date-picker
                v-model="submitForm.orderDate"
                style="width: 100%"
                type="date"
                placeholder="请选择订单日期"
                value-format="yyyy-MM-dd"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerId">
              <customer-query ref="customerQuery" v-model="submitForm.customerId" @choose="handleChooseCustomer" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优先级" prop="priority">
              <dict-select
                v-model="submitForm.priority"
                dict-key="priority"
                type="radio"
                placeholder="请选择优先级"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="info_group">
          <div class="info_section" />
          <div class="info_title">合计</div>
        </div>
        <el-row>
          <el-col :span="6">
            <el-statistic
              title="总数"
              group-separator=","
              :precision="2"
              :value="submitForm.totalCount"
            >
              <template slot="prefix">
                <i class="el-icon-money" style="color: red" />
              </template>
              <template slot="suffix">
                <i class="el-icon-money" style="color: red" />
              </template>
              <template slot="formatter">
                {{ submitForm.totalCount }}
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="含税总金额"
              group-separator=","
              :precision="2"
              :value="submitForm.totalAmount"
            >
              <template slot="prefix">
                <i class="el-icon-money" style="color: red" />
              </template>
              <template slot="suffix">
                <i class="el-icon-money" style="color: red" />
              </template>
              <template slot="formatter">
                <money-format v-model="submitForm.totalAmount" />
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="不含税总金额"
              group-separator=","
              :precision="2"
              :value="submitForm.unTaxTotalAmount"
            >
              <template slot="prefix">
                <i class="el-icon-money" style="color: red" />
              </template>
              <template slot="suffix">
                <i class="el-icon-money" style="color: red" />
              </template>
              <template slot="formatter">
                <money-format v-model="submitForm.unTaxTotalAmount" />
              </template>
            </el-statistic>
          </el-col>
        </el-row>
        <div class="info_group">
          <div class="info_section" />
          <div class="info_title">产品明细</div>
        </div>
        <el-alert v-if="submitForm.id && submitForm.orderState === '1'" :closable="false" type="error">已经在生产的订单不能修改产品明细</el-alert>
        <el-alert v-else-if="itemList.length!==0" type="warning" :closable="false">鼠标移动到产品属性、数量、含税单价、备注上可直接修改</el-alert>
        <el-table
          :data="itemList"
          style="width: 100%;"
          border
          @cell-mouse-enter="handleCellEnter"
          @cell-mouse-leave="handleCellLeave"
        >
          <el-table-column label="产品名称" prop="productName" min-width="80" />
          <el-table-column label="颜色" prop="color" min-width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.isEdit">
                <el-input v-model="scope.row.color" size="small" style="margin-left: 10px;width: 90px" />
              </div>
              <div v-else>
                {{ scope.row.color }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="材质" prop="color" min-width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.isEdit">
                <el-input v-model="scope.row.material" size="small" style="margin-left: 10px;width: 90px" />
              </div>
              <div v-else>
                {{ scope.row.material }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="尺码" prop="size" min-width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.isEdit">
                <el-input v-model="scope.row.size" size="small" style="margin-left: 10px;width: 90px" />
              </div>
              <div v-else>
                {{ scope.row.size }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="长度" prop="size" min-width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.isEdit">
                <el-input v-model="scope.row.length" size="small" style="margin-left: 10px;width: 90px" />
              </div>
              <div v-else>
                {{ scope.row.length }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" min-width="80">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.quantity"
                type="number"
                class="item"
                placeholder="请输入数量"
                @blur="handleTotalAmountChange"
              />
              <div v-else class="txt">
                {{ scope.row.quantity }}
                <dict-table-column v-model="scope.row.unit" dict-key="prod_unit" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" min-width="80">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.unitPrice"
                type="number"
                class="item"
                placeholder="请输入单价"
                @blur="handleTotalAmountChange"
              />
              <money-format v-else v-model="scope.row.unitPrice" class="txt" />
            </template>
          </el-table-column>
          <el-table-column label="总价" prop="amount" min-width="100">
            <template slot-scope="scope">
              <money-format v-model="scope.row.amount" class="txt" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" show-overflow-tooltip min-width="80">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.isEdit"
                v-model="scope.row.remark"
                class="item"
                placeholder="请输入备注"
              />
              <div v-else class="txt">{{ scope.row.remark }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="!submitForm.id" icon="el-icon-delete" @click="handleRemoveProduct(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <el-button v-if="!submitForm.id" icon="el-icon-plus" style="width: 100%;margin-bottom: 50px" @click="selectProduct">添加产品</el-button>
      </el-form>
    </el-card>
    <div v-if="moldTableVisible">
      <mold-module ref="moldModule" :visible="moldTableVisible" @close="handleMoldChange" />
    </div>
    <div v-if="productAttrVisible">
      <product-attribute-module ref="productAttrModule" :visible="productAttrVisible" @close="handleProductAttrChange" />
    </div>
    <div class="footer_div">
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { order_save, order_update, order_detail } from '@/api/sale/order'
import moment from 'moment'
import ProductAttributeModule from '@/modules/productAttributeModule.vue'
import MoldModule from '@/modules/moldModule.vue'

export default {
  name: 'SubmitModule',
  components: { MoldModule, ProductAttributeModule },
  data() {
    return {
      formLoading: false,
      submitForm: {
        orderNo: '',
        orderDate: '',
        customerId: '',
        priority: '0',
        remark: '',
        totalCount: '0',
        totalAmount: '0.00',
        unTaxTotalAmount: '0.00'
      },
      itemList: [],
      submitFormRules: {
        orderDate: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
        customerId: [{ required: true, message: '请输入客户名称', trigger: 'change' }],
        priority: [{ required: true, message: '请选择优先级', trigger: 'change' }]
      },
      moldTableVisible: false,
      loading: false,
      productAttrVisible: false
    }
  },
  mounted() {
    this.initValue()
  },
  methods: {
    selectProduct() {
      this.moldTableVisible = true
      this.$nextTick(() => {
        this.$refs.moldModule.doPage()
      })
    },
    getNowOrderDate() {
      return moment().format('YYYY-MM-DD')
    },
    initValue() {
      if (this.$route.query.id) {
        this.loading = true
        order_detail(this.$route.query.id).then(resp => {
          if (resp.success) {
            this.submitForm = resp.data
            this.$refs.customerQuery.init(this.submitForm.customerName)
            this.itemList = [JSON.parse(JSON.stringify(resp.data))]
            this.itemList.forEach(item => {
              item.isEdit = false
            })
            this.handleTotalAmountChange()
          }
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.submitForm.orderDate = this.getNowOrderDate()
      }
    },
    doSave() {
      this.formLoading = true
      let request = order_save
      if (this.submitForm.id) {
        request = order_update
      }
      this.submitForm.itemList = this.itemList
      request(this.submitForm).then(resp => {
        if (resp.success) {
          this.$message.success('操作成功')
          this.$refs.submitForm.resetFields()
          this.itemList = []
          this.$refs.customerQuery.resetQueryForm()
          this.submitForm.totalAmount = '0.00'
          this.submitForm.totalCount = '0'
          this.submitForm.unTaxTotalAmount = '0.00'
          this.submitForm.orderDate = this.getNowOrderDate()
        }
      }).finally(() => {
        this.formLoading = false
      })
    },
    // 表单提交
    handleSubmit() {
      this.$refs.submitForm.validate((valid) => {
        if (valid) {
          this.$confirm('是否确定录入订单,录入后可在订单列表查看', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.doSave()
          })
        }
      })
    },
    handleProductAttrChange(row) {
      this.productAttrVisible = false
      if (row) {
        row.isEdit = false
        this.itemList.push(row)
        this.handleTotalAmountChange()
      }
    },
    handleMoldChange(row) {
      this.moldTableVisible = false
      if (row) {
        this.productAttrVisible = true
        this.$nextTick(() => {
          this.$refs.productAttrModule.init(row)
        })
      }
    },
    handleTotalAmountChange() {
      if (this.itemList.length > 0) {
        this.$nextTick(() => {
          const totalAmount = this.itemList.reduce((sum, item) => sum + Number(item.unitPrice) * Number(item.quantity), 0)
          const totalCount = this.itemList.reduce((sum, item) => sum + Number(item.quantity), 0)
          this.itemList.forEach(e => {
            e.amount = (Number(e.unitPrice) * Number(e.quantity)).toFixed(2)
            e.unTaxPrice = (e.unitPrice - (Number(e.unitPrice) * Number(e.taxRate) / 100).toFixed(2)).toFixed(2)
            e.unTaxAmount = (Number(e.amount) - (Number(e.amount) * Number(e.taxRate) / 100).toFixed(2)).toFixed(2)
          })
          this.submitForm.totalAmount = String(totalAmount)
          this.submitForm.totalCount = String(totalCount)
          this.submitForm.unTaxTotalAmount = String(totalAmount - ((totalAmount * this.itemList[0].taxRate) / 100).toFixed(2))
        })
      } else {
        this.submitForm.totalAmount = 0
      }
    },
    handleRemoveProduct(row) {
      this.itemList.splice(this.itemList.indexOf(row), 1)
      this.handleTotalAmountChange()
    },
    /** 鼠标移入cell */
    handleCellEnter(row, column, cell, event) {
      row.isEdit = !this.submitForm.id || this.submitForm.orderState === '0'
    },
    /** 鼠标移出cell */
    handleCellLeave(row, column, cell, event) {
      row.isEdit = false
    },
    handleChooseCustomer(row) {
      if (row) {
        this.submitForm.customerId = row.id
      }
    }
  }
}
</script>

<style scoped lang="scss">
.item{
  width: 100px;
  /* 调整elementUI中样式 如果不需要调整请忽略 */
  .el-input__inner{
    height: 24px!important;
  }
}
.txt{
  line-height: 24px;
  padding: 0 9px;
  box-sizing: border-box;
}
</style>
